package common

import (
	"errors"
	"fmt"
	models "qianggougo/model"
	"strings"
	"time"

	"context"

	"qianggougo/config"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB
var RDB *redis.Client
var Ctx = context.Background()

/**
 * 连接mysql
 */
func InitDB() {
	cfg := config.AppConfig.MySQL
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
	// dsn := "root:root@tcp(localhost:3306)/gogame?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接数据库失败: " + err.Error())
	} else {
		fmt.Println("连接成功")
	}
}

/**
 * 连接redis
 */
func InitRedis() {
	cfg := config.AppConfig.Redis
	RDB = redis.NewClient(&redis.Options{
		Addr:     cfg.Addr,
		Password: cfg.Password,
		DB:       cfg.DB,
	})
	// RDB = redis.NewClient(&redis.Options{
	// 	Addr:     "114.132.235.219:6379",
	// 	Password: "lzt123456.",
	// 	DB:       2,
	// })
}

/**
 * 令牌认证
 */
func Auth(c *gin.Context) {
	authHeader := c.GetHeader("Authorization")
	// 获取 Authorization 头，判断是否为空
	if authHeader == "" {
		c.AbortWithStatusJSON(401, gin.H{"error": "Authorization 头部不存在，重新登录"})
		return
	}

	// 2. 检查是否是 Bearer Token 格式
	if !strings.HasPrefix(authHeader, "Bearer ") {
		c.AbortWithStatusJSON(401, gin.H{"error": "错误的 Authorization 格式，重新登录"})
		return
	}

	// 3. 提取 Token（去掉 "Bearer " 前缀）
	token := strings.TrimPrefix(authHeader, "Bearer ")

	var user models.User
	result := DB.Where("token = ?", token).First(&user)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			c.AbortWithStatusJSON(401, gin.H{"err": 1, "msg": "找不到token"})
		} else {
			c.AbortWithStatusJSON(500, gin.H{"err": 1, "msg": "查询有误"})
		}
		return
	}

	TokenExpiration := user.ExpirationAt // 将令牌过期时间转为时间戳
	timestamp := int(time.Now().Unix())  // 获取当前时间戳，转为int
	if TokenExpiration > timestamp {
		timestamp = timestamp + 60*60*24
		DB.Model(&user).Where("token = ?", token).Update("ExpirationAt", timestamp)
		c.Set("userid", user.ID)
		c.Next()
		return
	}

	c.AbortWithStatusJSON(401, gin.H{"err": 1, "msg": "token已过期，重新登录"})
}
